#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os

from generator import *

import sqlite3dbm
from sqlobject import *
from sqlobject.sqlbuilder import *

from bs4 import BeautifulSoup
from bottlenose import api
AMAZON_API = api.Amazon(AWS_KEY, SECRET_KEY, ASSOCIATE_TAG, Region="JP")


VIEWED = { 
        '0':u'非公開', 
        '1':u'公開',   
        '2':u'編集中',  
        '3':u'削除予定',
}

import isbn 

class ArticlesType(SQLObject):
    prefix = StringCol(alternateID=True,notNone=1)
    title = UnicodeCol(notNone=1)
    header = UnicodeCol(default=u'')
    lead = UnicodeCol(default=u'')
    description = UnicodeCol(default=u'')
    keyword = UnicodeCol(default=u'')
    context = PickleCol(default=None)
    idx = StringCol(alternateID=False,notNone=1)
    articles = MultipleJoin('Articles')
    groups = MultipleJoin('Groups',joinColumn="articlestype_id")
    categories = MultipleJoin('Categories',joinColumn="articlestype_id")

    def GetAmazonByASIN(self,_asin):
        chk = isbn.isValid( _asin )
        if chk:
            sidx = "Books"
            idtype = "ISBN"
            _asin = _asin.replace('-','')
        else:
            sidx = "All"
            idtype = "ASIN"
        
        if _asin == "" :
            return {}
        try:
            response = AMAZON_API.ItemLookup(ItemId=_asin, ResponseGroup="Medium",SearchIndex=sidx,IdType=idtype)
            soup = BeautifulSoup(response,fromEncoding="utf8")
            item = {}
            try:
                item['itemid'] = soup.find('itemid').string
                item['formattedprice'] = soup.find('formattedprice').string
                item['detailpageurl'] = soup.find('detailpageurl').string
                item['sku'] = soup.find('sku').string
                #item['content'] = soup.find('content').string
                item['title'] = soup.find('title').string
                #item['department'] = soup.find('department').string
                item['smallimage'] = soup.find('smallimage').url.string
                item['mediumimage'] = soup.find('mediumimage').url.string
                item['largeimage'] = soup.find('largeimage').url.string
            except:
                pass
            return item 
        except:
            return {}

    def GetPostById(self,_id):
        try:
            _id = int(_id)
        except:
            return None
        post = Posts.select( Posts.q.id == _id ).getOne(default=None)
        return post

    def GetArticlesType(self,_prefix= None ):
        at = ArticlesType.select( ArticlesType.q.prefix == _prefix ).getOne(default=None)
        return at

    def GetArticle(self,_prefix= None ):
        article = Articles.select( Articles.q.prefix == _prefix ).getOne(default=None)
        return article

    def GetGroupPostsByUpdated( self, _limit ):
        articles = Articles.select( Articles.q.type == self.id )
        posts = Posts.select( AND( IN(Posts.q.article,articles) , Posts.q.viewed == 1 )  ).limit(_limit).orderBy('-date')
        return posts

    def GetPostsByKey( self, _prefix, _key , _limit = 10):
        if _key == None:
            return None 
        article = Articles.select( Articles.q.prefix == _prefix ).getOne(default=None)
        if article :
            posts = Posts.select( AND( Posts.q.article == article ,Posts.q.key == _key,  Posts.q.viewed == 1 )).limit(_limit).orderBy('-date')
        else:
            at = ArticlesType.select( ArticlesType.q.prefix == _prefix ).getOne(default=None)
            articles = Articles.select( Articles.q.type == at )
            posts = Posts.select( AND( IN(Posts.q.article,articles) ,Posts.q.key == _key, Posts.q.viewed == 1 )  ).limit(_limit).orderBy('-date')
        return posts

    def GetPaneoField( self, prefix , slug , paneo_name ,ext = 'string'):
        if prefix == 'page':
            dic = sqlite3dbm.sshelve.open(PANEO_DB)
            pages = dic.get('pages')
            fields = dic.get('fields')
            dic.close
            if paneo_name == 'title':
                return pages.get(slug,'').TITLE
            id = slug
        else:
            post = Posts.select(Posts.q.slug == slug).getOne(default=None)
            if not post :
                return ""
            id = post.id
            fields = post.fields
            if paneo_name == 'title':
                return post.header
            if paneo_name == 'header':
                return post.lead
            if paneo_name == 'lead':
                return post.title 
        if ext == 'href':
            k = 'a_%s_%s_%s'%(prefix,id,paneo_name)
        else:
            k = 'txt_%s_%s_%s'%(prefix,id,paneo_name)
        if ext == 'string':
            return fields.get( k , {} ).get('string','')
        else:
            return fields.get( k , {} ).get('ext',{}).get(ext,'')

class Articles(SQLObject):
    type = ForeignKey('ArticlesType',notNone=1)
    prefix = StringCol(alternateID=True,notNone=1)
    title = UnicodeCol(notNone=1)
    
    header = UnicodeCol(default=u'')
    lead = UnicodeCol(default=u'')
    description = UnicodeCol(default=u'')
    keyword = UnicodeCol(default=u'')
    context = PickleCol(default=None)

    password = StringCol(notNone=1)
    template_set = StringCol(notNone=1)
    template_system_use = BoolCol(notNull=True, default=False)
    default_template = StringCol(default=u'skelton')
    img = PickleCol(default=None)
    posts = MultipleJoin('Posts',joinColumn="article_id")

    def GetPostsByUpdated( self, _limit ):
        posts = Posts.select( AND( Posts.q.article == self , Posts.q.viewed == 1 )).limit(_limit).orderBy('-date')
        return posts


class Posts(SQLObject):

    class sqlmeta:
        lazyUpdate = True
        cacheValues = False

    article = ForeignKey('Articles',notNone=1)
    slug = UnicodeCol(alternateID=True,notNone=1)
    key = StringCol(notNone=1)

    date = DateTimeCol(notNone=1,default=DateTimeCol.now)

    title = UnicodeCol(default=u'')
    header = UnicodeCol(default=u'')
    lead = UnicodeCol(default=u'')
    description = UnicodeCol(default=u'')
    keyword = UnicodeCol(default=u'')
    context = PickleCol(default=None)

    password = StringCol(notNone=1)
    viewed = IntCol(notNone=0, default=1)

    fields = PickleCol(default=None)
    rawtext = UnicodeCol(default="")
    template = StringCol(notNone=1)
    group = ForeignKey('Groups',notNone=0)
    categories = RelatedJoin('Categories')
    label1 = UnicodeCol(default="")
    label2 = UnicodeCol(default="")
    label3 = UnicodeCol(default="")
    updated = DateTimeCol(notNone=1,default=DateTimeCol.now)
    created = DateTimeCol(notNone=1,default=DateTimeCol.now)
    #INDEX
    article_index = DatabaseIndex('article')
    slug_index = DatabaseIndex('slug')
    key_index = DatabaseIndex('key')
    group_index = DatabaseIndex('group')
    date_index = DatabaseIndex('date')
    viewed_index = DatabaseIndex('viewed')
    label1_index = DatabaseIndex('label1')
    label2_index = DatabaseIndex('label2')
    label3_index = DatabaseIndex('label3')
    updated_index = DatabaseIndex('updated')
#    categories = SQLRelatedJoin(    'Categories',
#                                    intermediateTable='posts_categories',
#                                    createRelatedTable=False)

    def has_category(self,_id):
        for c in self.categories:
            if c.id == _id:
                return c
        return None

    def GetField(self , _name , ext = 'string'):
        if not self.fields:
            return ""
        if ext == 'href':
            f = self.fields.get('a_post_%s_%s'%(self.id,_name))
        else:
            f = self.fields.get('txt_post_%s_%s'%(self.id,_name))
        if f :
            if ext == 'string':
                return f.get('string')
            else:
                return f.get('ext',{}).get(ext,'')
        return ""

    def GetImageTag(self, _name , _opt = "" ):
        if _opt != "":
            if os.path.exists( PANEO_SITE_DATA_DIR + '/_tmp/cache/img/img_post_%s_%s_%s' % ( self.id, _name, _opt ) ):
                return '<img src="/' + PANEO_SITE_DIR + '/_tmp/cache/img/img_post_%s_%s_%s" alt="%s"/>' % ( self.id, _name, _opt,self.title )
                
        if os.path.exists( PANEO_SITE_DATA_DIR + '/_tmp/cache/img/img_post_%s_%s' % ( self.id, _name ) ):
            return '<img src="/' + PANEO_SITE_DIR + '/_tmp/cache/img/img_post_%s_%s" alt="%s"/>' % ( self.id, _name ,self.title)

        if os.path.exists( PANEO_SITE_DATA_DIR + 'img/img_post_%s_%s' % ( self.id , _name ) ):
            if _opt != "":
                return '<img src="/img/img_post_%s_%s/%s/" title="%s">' % ( self.id, _name , _opt ,self.title )
            else:
                return '<img src="/img/img_post_%s_%s" title="%s">' % ( self.id, _name , self.title )
        else:
            return '<img src="/common/js/paneoimg.js/%s/" title="%s">' % ( _opt , self.article.title )

class Groups(SQLObject):
    code = StringCol(alternateID=False,notNone=1)
    parent = ForeignKey("Groups")
    label = UnicodeCol(default=u'',alternateID=False,notNone=1)
    idx = IntCol(notNone=False)
    viewed = IntCol(notNone=0, default=1)
    articlestype = ForeignKey('ArticlesType',notNone=0)
    posts = MultipleJoin('Posts')
    #INDEX
    code_index = DatabaseIndex('code')
    idx_index = DatabaseIndex('idx')
    parent_index = DatabaseIndex('parent')
    articlestype_index = DatabaseIndex('articlestype')

class Categories(SQLObject):
    code = StringCol(alternateID=False,notNone=1)
    parent = ForeignKey("Categories")
    label = UnicodeCol(default=u'',alternateID=False,notNone=1)
    idx = IntCol(notNone=False)
    viewed = IntCol(notNone=0, default=1)
    articlestype = ForeignKey('ArticlesType',notNone=0)
    posts = RelatedJoin('Posts')
    #INDEX
    code_index = DatabaseIndex('code')
    idx_index = DatabaseIndex('idx')
    parent_index = DatabaseIndex('parent')
    articlestype_index = DatabaseIndex('articlestype')
#    posts = SQLRelatedJoin(    'Posts',
#                                intermediateTable='posts_categories',
#                                createRelatedTable=False)

#class PostsCategories(SQLObject):
#    posts = ForeignKey('Posts', notNull=True, cascade=True)
#    categories = ForeignKey('Categories', notNull=True, cascade=True)
#    active = BoolCol(notNull=True, default=False)
#    #unique = index.DatabaseIndex(Posts, Categories, unique=True)


